<template>
  <div class=" container-image">
    <el-card>
      <div slot="header">
        <my-bread>素材管理</my-bread>
      </div>
      <div class="btn-box">
        <el-radio-group
          @change="toggleList()"
          v-model="reqParams.collect"
          size="small"
        >
          <el-radio-button :label="false">全部</el-radio-button>
          <el-radio-button :label="true">收藏</el-radio-button>
        </el-radio-group>
        <el-button @click="openDialog()" style="float:right" type="success" size="small">添加素材</el-button>
        <div class="list-box">
          <div class="item-box" v-for="item in images" :key="item.id">
            <img :src="item.url" alt />
            <div class="option" v-if="!reqParams.collect">
              <span
                @click="toggleStatus(item)"
                class="el-icon-star-off"
                :class="{ red: item.is_collected }"
              ></span>
              <span class="el-icon-delete" @click="delImage(item.id)"></span>
            </div>
          </div>
        </div>
      </div>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="reqParams.per_page"
        :current-page="reqParams.page"
        @current-change="changePager"
      ></el-pagination>
    </el-card>
    <!-- 对话框 -->
    <el-dialog title="上传素材" :visible.sync="dialogVisible" width="300px">
            <!-- 上传组件 -->
      <el-upload
        class="avatar-uploader"
        action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
        name="image"
        :headers = "headers"
        :on-success = "uploadSuccess"
        :show-file-list="false">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>

    </el-dialog>
  </div>
</template>

<script>
import auth from '@/utils/auth'
export default {
  name: "page-image",
  data() {
    //   这里面放的是对象
    return {
      // 上传请求头对象
      headers: { Authorization: `Bearer ${auth.getUser().token}` },
      // 查询条件
      reqParams: {
        // 是否查的收藏，true查询收藏图片 false查询全部图片
        collect: false,
        page: 1,
        per_page: 10
      },
      // 素材
      images: [],
      total: 0,
      // 控制对话框显示隐藏
      dialogVisible: false,
    //预览图片地址
     imageUrl : null
    };
  },
  created() {
    this.getImages();
  },
  methods: {
    //   上传成功 response 是上传成功后台返回的数据
    uploadSuccess (response) {
        // 提示+预览
        this.$message.success('上传素材成功')
        this.imageUrl = response.data.imageUrl
        // 3s后：关闭对话框+更新列表
        window.setTimeout(() => {
            this.dialogVisible = false
            this.getImages()
        },3000)
    },
    // 打开对话框
    openDialog() {
      this.dialogVisible = true
      this.imageUrl = null
    },
    //   收藏
    async toggleStatus(item) {
      // 修改后的状态
      const updatedStatus = !item.is_collected
      try {
        // 发请求
        await this.$http.put(`user/images/${item.id}`, {
          // 和当前图片状态取反即可，当前已收藏--->取消收藏  当前未收藏--->添加收藏
          collect: updatedStatus
        })
        // success 绿色的  error 红色的  在弹出组件中有介绍
        // 成功提示
        this.$message.success(updatedStatus ? "添加收藏成功" : "取消收藏成功");
        // 根据修改后的状态去改 星星的颜色，修改图片数据对应的状态is_collected即可
        item.is_collected = updatedStatus;
      } catch (e) {
        // 失败提示
        this.$message.error(updatedStatus ? "添加收藏失败" : "取消收藏失败");
      }
    },
    //   删除素材
    delImage(id) {
      // 确认框
      this.$confirm("此操作将永久删除图片素材, 是否继续?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            //   删除请求
            //  ``下面是模板拼接的写法
            await this.$http.delete(`user/images/${id}`)
            this.$message.success("删除素材成功")
            this.getImages()
          } catch (e) {
            this.$message.error("删除素材失败")
          }
        })
        .catch(() => {});
    },
    // 切换全部和收藏
    toggleList() {
      this.reqParams.page = 1
      this.getImages()
    },
    // 切换分页
    changePager(newPage) {
      this.reqParams.page = newPage;
      this.getImages()
    },
    async getImages() {
      const res = await this.$http.get("user/images", {
        params: this.reqParams
      });
      this.images = res.data.data.results;
      // 设置总条数
      this.total = res.data.data.total_count;
    }
  }
};
</script>

<style scoped lang="less">
.list-box {
  margin-top: 20px;
  .item-box {
    display: inline-block;
    width: 180px;
    height: 180px;
    margin-right: 60px;
    border: 1px dashed #ddd;
    position: relative;
    margin-bottom: 20px;
    img {
      display: block;
      width: 100%;
      height: 100%;
    }
    .option {
      width: 100%;
      height: 30px;
      position: absolute;
      left: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.3);
      text-align: center;
      line-height: 30px;
      span {
        color: #fff;
        margin: 0 20px;
        // 不加&解析后：span .red{} 后代选择器
        // 加上&节后后：span.red{}  交集选择器
        &.red {
          color: red;
        }
      }
    }
  }
}
</style>
